<?php


class Qq{
    
    private $_error;
    private $appid;
    private $appsecret;

    public function __construct() {
        $this->appid = Configure::get('qq.appid');
        $this->appsecret = Configure::get('qq.appsecret');
    }

    public function getAppId() {
        return $this->appid;
    }
    
    public function getOpenid($access_token) {
        if(!$access_token) {
            $this->_error = 'access_token获取失败,登录失败';
            return false;
        }
        $url = 'https://graph.qq.com/oauth2.0/me?access_token='.$access_token;
        $result = Curl::get($url);
        $result = json_decode(trim(substr($result, 9), " );\n"), true);
        if(isset($result['openid'])) {
            return $result['openid'];
        }
        $this->_error = '获取openid失败,请重新登录';
        return false;
    }
    
    public function getUserInfo($access_token, $openid) {
        $url = 'https://graph.qq.com/user/get_user_info';
        $data = [
            'oauth_consumer_key' => $this->appid,
            'access_token' => $access_token,
            'openid' => $openid,
            'format' => 'json'
        ];
        $result = Curl::get($url, $data);
        $result = json_decode($result, true);
        if(!isset($result['ret']) || $result['ret'] == 0){
            $user_info = [
                'openid' => $openid,
                'nickname' => $result['nickname'],
                'avatar' => $result['figureurl_2'],
                'sex' => $result['gender']=='女'?2:1
            ];
            return $user_info;
        }
        $this->_error='获取用户信息失败,请稍后重试';
        return false;
    }
    
    public function getError() {
        return $this->_error;
    }
}